package com.simnim.io.accessibility;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.R.string;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;

public class SearchYouTubeActivity extends ListActivity implements OnItemClickListener {
	private ArrayAdapter<String> aa;
	private String query;
	private ArrayList<VideoTag> entries;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_view);
		
		query = getIntent().getStringExtra("query");
		query.replaceAll(" ", "+");
		
		aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1);
		
		getListView().setOnItemClickListener(this);
		setListAdapter(aa);
		
		SearchYouTubeTask task = new SearchYouTubeTask();
		task.execute();
	}
	
	public void onItemClick(AdapterView<?> a, View v, int position, long id) {
		Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=" + ((VideoTag)entries.get(position)).videoID));
		startActivity(i);
	}
	
	private class SearchYouTubeTask extends AsyncTask<String, Void, Void> {
		ProgressDialog prog;
		@Override
		protected void onPreExecute() {
			prog = ProgressDialog.show(SearchYouTubeActivity.this, "Searching", "Please wait, searching YouTube...", true);
		}
		
		@Override
		protected Void doInBackground(String... params) {
			try {
				HttpClient client = new DefaultHttpClient();
				HttpGet request = new HttpGet();
				request.setURI(new URI("http://gdata.youtube.com/feeds/api/videos?q=" + query + "&caption&v=2"));
				HttpResponse response = client.execute(request);
				BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
				XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
				XmlPullParser xpp = factory.newPullParser();
				xpp.setInput(in);
				xpp.next();
				
				int event = xpp.getEventType();
				boolean inEntry = false, inTitle = false, inID = false;
				entries = new ArrayList<VideoTag>();
				VideoTag tag = null;
				while(event != XmlPullParser.END_DOCUMENT) {
					String name = xpp.getName();
					if(event == XmlPullParser.START_TAG) {
						if(!inEntry) {
							if(name.equals("entry")) {
								inEntry = true;
								tag = new VideoTag();
							}
						}else {
							if(name.equals("media:title")) {
								inTitle = true;
							}else if(name.equals("yt:videoid")) {
								inID = true;
							}
						}
					}else if(event == XmlPullParser.END_TAG) {
						if(inEntry && name.equals("entry")) {
							entries.add(tag);
							inEntry = false;
						}
						if(inTitle)
							inTitle = false;
						if(inID)
							inID = false;
					}else if(event == XmlPullParser.TEXT) {
						if(inTitle) {
							tag.title = xpp.getText();
						}else if(inID) {
							tag.videoID = xpp.getText();
						}
					}
					
					xpp.next();
					event = xpp.getEventType();
				}
			} catch (URISyntaxException e) {
				Log.e("Search", "", e);
			}catch(ClientProtocolException e) {
				Log.e("Search", "", e);
			}catch(IOException e) {
				Log.e("Search", "", e);
			}catch(XmlPullParserException e) {
				Log.e("Search", "", e);
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			prog.dismiss();
			aa.clear();
			for(VideoTag entry : entries) {
				aa.add(entry.title);
			}
		}
	}
	
	public class VideoTag {
		public String videoID;
		public String title;
	}
}
